package com.kq.servlet.kqctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.PreloadListener;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.utils.JsonUtil;

public class doLogin extends HttpServlet
{
  public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    response.setCharacterEncoding("UTF-8");
    String name = request.getParameter("name");
    String pswd = request.getParameter("pswd");

    HtmlPage rootPage = PreloadListener.rootPage;
    String html = "";
    String ajaxContent = "$.ajax({url:'http://erp.kanq.com.cn:806/pages/user_login.action',type:'get',dataType:'json',";
    ajaxContent = ajaxContent + "data:{'name':'" + name + "','pswd':'" + pswd + "'},async:false,cache:false,";
    ajaxContent = ajaxContent + "error: function(xhr){$('body').html(xhr.responseText);}});";
    rootPage.executeJavaScript(ajaxContent);
    try {
      Thread.sleep(100L);
    }
    catch (Exception localException) {
    }
    html = rootPage.getBody().getTextContent();
    int i = 0;
    while ((html.indexOf("/system/gateway/index.html?") == -1) && (html.indexOf("错误") == -1) && (html.indexOf("存在") == -1)) {
      if (i > 20)
        break;
      try
      {
        Thread.sleep(100L);
      }
      catch (Exception localException1) {
      }
      html = rootPage.getBody().getTextContent();
      i++;
      System.out.println("进行了" + i + "次重试！");
    }
    String userId = "";
    String errorLog = "";
    Map result = new HashMap();
    if (html.indexOf("?") != -1) {
      userId = html.split("\\?")[1];
      PreloadListener.loginInfo.put("name", name);
      PreloadListener.loginInfo.put("pswd", pswd);
      PreloadListener.loginInfo.put("id", userId);
    } else {
      errorLog = html.split(";")[1];
    }

    if (errorLog != "") {
      result.put("log", errorLog);
      result.put("status", "false");
    } else {
      result.put("log", "登陆成功！");
      result.put("status", "true");
      result.put("Info", PreloadListener.loginInfo);
    }
    System.out.println(result);
    PrintWriter out = response.getWriter();
    out.write(JsonUtil.stringify(result));
    out.flush();
  }
}